package com.defect.service.securityService.securityServiceImpl;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;

public class DecisionManager implements AccessDecisionManager {
    private AntPathMatcher apm = new AntPathMatcher();
    private String[] urls;

    public DecisionManager() {
        this.urls = new String[]{"/login.html", "/login", "/css/*", "/js/*", "/images/*", "/code*","/favicon.ico"};
    }

    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        String url = ((FilterInvocation) o).getRequestUrl();
        for (String u : urls) {
            if (apm.match(u , url)) {
                return;
            }
        }
        if(authentication instanceof AnonymousAuthenticationToken){
            throw new AccessDeniedException("未登录");
        }
        System.out.println(collection.iterator().next());
        System.out.println(collection.iterator().next().equals("login"));
        if(collection!=null && collection.size()==1 && collection.iterator().next().equals("login")){
            System.out.println("放行");
            return;
        }
        for(ConfigAttribute ca : collection){
            String c = ca.getAttribute();
            for(GrantedAuthority ga : authentication.getAuthorities()){
                if(ga.getAuthority().equals(c)){
                    return;
                }
            }
        }
        throw new AccessDeniedException("没有访问权限");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
